package com.ruoyi.business.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.ruoyi.business.domain.HistoricActivity;
import com.ruoyi.business.domain.ServiceItem;
import com.ruoyi.business.service.IDefinitionNodeService;
import com.ruoyi.business.service.IProcessService;
import com.ruoyi.business.service.IServiceItemService;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysUserService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.business.mapper.CarPackageAuditMapper;
import com.ruoyi.business.domain.CarPackageAudit;
import com.ruoyi.business.service.ICarPackageAuditService;
import com.ruoyi.common.core.text.Convert;
import org.springframework.transaction.annotation.Transactional;

/**
 * 审核列表Service业务层处理
 * 
 * @author wolfcode
 * @date 2021-07-20
 */
@Service
public class CarPackageAuditServiceImpl implements ICarPackageAuditService 
{
    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;
    @Autowired
    private IProcessService processService;
    @Autowired
    private IServiceItemService serviceItemService;
    @Autowired
    private IDefinitionNodeService definitionNodeService;
    @Autowired
    private ISysUserService userService;

    /**
     * 查询审核列表
     * 
     * @param id 审核列表ID
     * @return 审核列表
     */
    @Override
    public CarPackageAudit selectCarPackageAuditById(Long id)
    {
        return carPackageAuditMapper.selectCarPackageAuditById(id);
    }

    /**
     * 查询审核列表列表
     * 
     * @param carPackageAudit 审核列表
     * @return 审核列表
     */
    @Override
    public List<CarPackageAudit> selectCarPackageAuditList(CarPackageAudit carPackageAudit)
    {
        carPackageAudit.setCreateBy(ShiroUtils.getUserId().toString());
        List<CarPackageAudit> carPackageAudits = carPackageAuditMapper.selectCarPackageAuditList(carPackageAudit);
        for(CarPackageAudit audit:carPackageAudits){
            audit.setServiceItem(JSON.parseObject(audit.getServiceItemInfo(), ServiceItem.class));
            //根据数据中的流程实例id查询任务名称
            Task currentTask = processService.getTaskByProcessInstanceId(audit.getInstanceId());
            if(currentTask!=null){
                //currentTask!=null,说明任务未结束
                audit.setTaskId(currentTask.getId());
                audit.setTaskName(currentTask.getName());
            }else{
                //currentTask==null,说明任务已经结束
                audit.setTaskName("任务结束");
            }

        }
        return carPackageAudits;
    }

    /**
     * 新增审核列表
     * 
     * @param carPackageAudit 审核列表
     * @return 结果
     */
    @Override
    public int insertCarPackageAudit(CarPackageAudit carPackageAudit)
    {
        carPackageAudit.setCreateTime(DateUtils.getNowDate());
        return carPackageAuditMapper.insertCarPackageAudit(carPackageAudit);
    }

    /**
     * 修改审核列表
     * 
     * @param carPackageAudit 审核列表
     * @return 结果
     */
    @Override
    public int updateCarPackageAudit(CarPackageAudit carPackageAudit)
    {
        return carPackageAuditMapper.updateCarPackageAudit(carPackageAudit);
    }

    /**
     * 删除审核列表对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteCarPackageAuditByIds(String ids)
    {
        return carPackageAuditMapper.deleteCarPackageAuditByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除审核列表信息
     * 
     * @param id 审核列表ID
     * @return 结果
     */
    @Override
    public int deleteCarPackageAuditById(Long id)
    {
        return carPackageAuditMapper.deleteCarPackageAuditById(id);
    }

    @Override
    @Transactional
    public void cancelApply(String instanceId, Long carPackageAuditId) {
        //1.把快照表的信息(状态修改成撤销,审核人设置为空)
        CarPackageAudit audit = carPackageAuditMapper.selectCarPackageAuditById(carPackageAuditId);
        audit.setStatus(CarPackageAudit.STATUS_CANCEL);
        audit.setAuditors("");
        carPackageAuditMapper.updateCarPackageAudit(audit);
        //2.把服务项的状态修改成初始化
        //目前状态  审核中
        ServiceItem item = JSON.parseObject(audit.getServiceItemInfo(),ServiceItem.class);
        item.setAuditStatus(ServiceItem.AUDITSTATUS_INIT);//状态修改为初始化
        serviceItemService.updateServiceItemNoCondition(item);//重写方法,之前的方法会判断状态,如果处于审核中是不允许修改的.
        //3.删除流程
        processService.deleteProcessInstance(instanceId);
    }

    @Override
    public List<CarPackageAudit> selectTodoList(CarPackageAudit carPackageAudit) {
        //获取到当前登录用的ID,根据用户id查询待办任务
        String userId = ShiroUtils.getUserId().toString();
        //查询符合条件的记录有多少条
        Long count = processService.getTodoTaskCount(CarPackageAudit.DEFINITION_KEY,userId);
        if(count>0){
            //获取前台传入的pageNum和PageSize
            PageDomain pageDomain = TableSupport.buildPageRequest();
            Integer pageNum = pageDomain.getPageNum();
            Integer pageSize = pageDomain.getPageSize();
            Integer startNum = (pageNum-1)*pageSize;
            //如果符合条件的记录数大于0,才进行集合的查询
            List<Task> taskList = processService.selectTodoTaskList(
                        CarPackageAudit.DEFINITION_KEY,//哪个流程
                        userId,//查询谁的任务
                        startNum,//分页中起始位置
                        pageSize);//查询多少条
            //需要返回给前台的数据
            List<CarPackageAudit> resultList = new ArrayList();
            for(Task task:taskList){
                ProcessInstance instance = processService.getProcessInstanceById(task.getProcessInstanceId());
                String businessKey = instance.getBusinessKey();
                CarPackageAudit audit = carPackageAuditMapper.selectCarPackageAuditById(Long.parseLong(businessKey));
                audit.setServiceItem(JSON.parseObject(audit.getServiceItemInfo(),ServiceItem.class));
                audit.setTaskId(task.getId());//设置任务Id
                audit.setTaskName(task.getName());//设置任务名称
                resultList.add(audit);
            }
            //将数据封装成page对象,里面包含总数,分页条数,页码.
            Page page = new Page();
            page.setTotal(count);
            page.setPageNum(pageNum);
            page.setPageSize(pageSize);
            page.addAll(resultList);
            return page;
        }else{
            return Collections.EMPTY_LIST;
        }
    }

    @Override
    @Transactional
    public void complete(String taskId, Boolean auditStatus, String comment) {
        //任务处理
        Task task = processService.getTaskByTaskId(taskId);
        ProcessInstance instance= null;
        ProcessInstance processInstance = processService.getProcessInstanceById(task.getProcessInstanceId());
        String businessKey = processInstance.getBusinessKey();
        //  任务属于候选人任务,先领取.
        //  给任务添加批注信息
        //  给任务添加流程变量 流程变量的名字当前处理任务的id  流程的值 auditStatus
        processService.claimAndComplete(task,ShiroUtils.getUserId().toString(),auditStatus,comment);
        //判断流程是否已经结束了.
        //如果流程结束了,审核就通过
        //如何判断流程已经结束了?
        Task nextTask = processService.getTaskByProcessInstanceId(task.getProcessInstanceId());
        //根据流程实例ID获取下一个节点. 下一个节点为空: 流程已经结束,审核通过  下一个不为空: 流程没有结束
        CarPackageAudit audit = carPackageAuditMapper.selectCarPackageAuditById(Long.parseLong(businessKey));
        if(nextTask==null){
            //下一个节点为空: 流程已经结束
            //    需要获取业务key才可以获取到carPackageAudit对象
            //    t_car_package_audit和t_service_item修改审核状态
            audit.setStatus(CarPackageAudit.STATUS_PASS);//审核通过
            audit.setAuditors("");
            //更新服务项
            ServiceItem item = JSON.parseObject(audit.getServiceItemInfo(),ServiceItem.class);
            item.setAuditStatus(ServiceItem.AUDITSTATUS_APPROVED);
            serviceItemService.updateServiceItemNoCondition(item);
        }else{
            //下一个节点不为空: 流程节点没有结束
            if(auditStatus){
                //    如果auditStatus为true
                //        根据下一个节点的Id在t_definition_node寻找该节点的审核人,给该节点设置候选人
                List<String> userNameList = new ArrayList<>();
                String taskDefinitionKey = nextTask.getTaskDefinitionKey();
                List<SysUser> auditors = definitionNodeService.queryByTaskDefinitionKey(taskDefinitionKey);
                for(SysUser user:auditors){
                    //给下一个任务设置对应候选人
                    processService.addCandidateUser(nextTask,user.getUserId());
                    userNameList.add(user.getUserName());
                }
                //保存快照表中
                audit.setAuditors(JSON.toJSONString(userNameList));
            }else{
                //    如果auditStatus为false
                //        获取到该流程发起人,给当前节点设置对应的候选人为当前流程发起人
                processService.addCandidateUser(nextTask,Long.parseLong(audit.getCreateBy()));
                //        t_car_package_audit状态修改成审核拒绝 1
                audit.setAuditors(audit.getCreateByName());
                audit.setStatus(CarPackageAudit.STATUS_REJECT);
            }
        }
        carPackageAuditMapper.updateCarPackageAudit(audit);
    }

    @Override
    @Transactional
    public void serviceItemsUpdate(Long carPackageAuditId, ServiceItem serviceItem) {
        serviceItemService.updateServiceItemNoCondition(serviceItem);
        CarPackageAudit audit = carPackageAuditMapper.selectCarPackageAuditById(carPackageAuditId);
        audit.setServiceItemInfo(JSON.toJSONString(serviceItem));
        carPackageAuditMapper.updateCarPackageAudit(audit);
    }

    @Override
    @Transactional
    public void reApply(String taskId, Long carPackageAuditId) {
        //添加批注,领取任务,完成任务
        Task task = processService.getTaskByTaskId(taskId);
        //设置新的流程变量
        CarPackageAudit audit = carPackageAuditMapper.selectCarPackageAuditById(carPackageAuditId);
        ServiceItem item = JSON.parseObject(audit.getServiceItemInfo(),ServiceItem.class);
        processService.setVariable(task.getId(),"money",item.getDiscountPrice().longValue());

        processService.claimAndComplete(task,ShiroUtils.getUserId().toString(),"重新申请");
        //查询下一个节点,查询对应候选人,给任务添加候选人
        //根据流程实例ID查询当前流程正在走的节点(任务)
        Task nextTask = processService.getTaskByProcessInstanceId(task.getProcessInstanceId());
        String taskDefinitionKey = nextTask.getTaskDefinitionKey();
        List<SysUser> sysUsers = definitionNodeService.queryByTaskDefinitionKey(taskDefinitionKey);
        List<String> auditors = new ArrayList<>();
        for(SysUser user:sysUsers){
            //给下一个任务设置候选人
            processService.addCandidateUser(nextTask,user.getUserId());
            auditors.add(user.getUserName());
        }
        //根据carPackageAuditId查询carPackageAudit对象,更新状态(审核中)
        //更新carPackageAudit对象的auditors字段
        
        audit.setStatus(CarPackageAudit.STATUS_IN_ROGRESS);
        audit.setAuditors(JSON.toJSONString(auditors));
        carPackageAuditMapper.updateCarPackageAudit(audit);
    }

    @Override
    public List<CarPackageAudit> selectDoneList(CarPackageAudit carPackageAudit) {
        //获取当前登录用户的ID
        String userId = ShiroUtils.getUserId().toString();
        //获取已办任务的总数
        long count =  processService.getHistoricTaskCount(CarPackageAudit.DEFINITION_KEY,userId);
        if(count>0){
            //获取前台传入的pageNum和PageSize
            PageDomain pageDomain = TableSupport.buildPageRequest();
            Integer pageNum = pageDomain.getPageNum();
            Integer pageSize = pageDomain.getPageSize();
            Integer startNum = (pageNum-1)*pageSize;
            List<HistoricTaskInstance> historicTaskInstanceList =
                    processService.selectHistoricTaskList(
                            CarPackageAudit.DEFINITION_KEY,//流程定义key
                            userId,//用户id
                            startNum,//起始位置
                            pageSize//每页条数
                            );
            List<CarPackageAudit> resultList = new ArrayList<>();
            for(HistoricTaskInstance task:historicTaskInstanceList){
                //如果任务已经完成,通过下面方法是获取不到流程实例对象
                HistoricProcessInstance instance = processService.getHistoricProcessInstanceById(task.getProcessInstanceId());
                String businessKey = instance.getBusinessKey();
                CarPackageAudit audit = carPackageAuditMapper.selectCarPackageAuditById(Long.parseLong(businessKey));
                audit.setServiceItem(JSON.parseObject(audit.getServiceItemInfo(),ServiceItem.class));//JSON字符串转成对象
                audit.setTaskName(task.getName());
                audit.setTaskId(task.getId());
                audit.setDoneTime(task.getEndTime());//任务完成时间
                resultList.add(audit);
            }
            Page page = new Page();
            page.setPageNum(pageNum);
            page.setPageSize(pageSize);
            page.addAll(resultList);
            return page;
        }else{
            return Collections.EMPTY_LIST;
        }
    }

    @Override
    public List<HistoricActivity> listHistory(String instanceId) {
        List<HistoricActivityInstance> historicActivityInstances = processService.selectHistoricActivityList(instanceId);
        //返回的结果集
        List<HistoricActivity> resultList = new ArrayList<>();
        for(HistoricActivityInstance instance:historicActivityInstances){
            HistoricActivity activity = new HistoricActivity();
            //把instance的所有属性值赋值给activity
            BeanUtils.copyProperties(instance,activity);
            //查询批注信息
            String comment = processService.getComment(activity.getTaskId());
            activity.setComment(comment);
            //设置任务处理人
            String assignee = activity.getAssignee();
            if(StringUtils.isNotEmpty(assignee)){
                SysUser sysUser = userService.selectUserById(Long.parseLong(assignee));
                activity.setAssigneeName(sysUser.getUserName());
            }
            resultList.add(activity);
        }
        return resultList;
    }
}
